﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace asp.netWebFroms
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillDataTable();
            }
        }


        private void FillDataTable()
        {
           
            var sql = string.Format("select id, Title 标题,Content 内容, Author 作者,Remarks 备注 from Articles");
            var dt = DbHelper.GetDataTable(sql);
                        
            GridView1.DataBind();
        }

        //取消
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            FillDataTable();
        }
        //编辑
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            FillDataTable();
        }

        //删除
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetDataValue(e.RowIndex, 1);
            var sql = string.Format("delete from Articles where Id = '{0}'", id);
            DbHelper.AddOrDeleteOrUp(sql);

            GridView1.EditIndex = -1;
            FillDataTable();


        }

        private string GetDataValue(int rowIndex,int cellIndex)
        {
            var control = GridView1.Rows[rowIndex].Cells[cellIndex];
            var res = control.Controls.Count > 0 ? ((TextBox)control.Controls[0]).Text : control.Text;
            return res;
        }

        //更新
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var id = GetDataValue(e.RowIndex, 1);
            var titles = GetDataValue(e.RowIndex, 2);
            var contents = GetDataValue(e.RowIndex, 3);
            var authors = GetDataValue(e.RowIndex, 4);
            var remarks = GetDataValue(e.RowIndex, 5);
            var sql = string.Format("update Articles set Title ='{0}', Content = '{1}', Author = '{2}', Remarks = '{3}' where id = '{4}'", titles, contents, authors, remarks,id );
            
            DbHelper.AddOrDeleteOrUp(sql);
   
            GridView1.EditIndex = -1;
            FillDataTable();
        }

        protected void add_Click(object sender, EventArgs e)
        {
            var sql = this.FillDataTable;
            var dt = sql.Copy();

            dt.Rows.Add(dt.NewRow());

            GridView1.DataSource = dt;
            GridView1.DataBind();

            GridView1.EditIndex = dt.Rows.Count - 1;

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}